﻿using Microsoft.Extensions.Logging;
using JESAI.Application.Abstractions.Sys;
using JESAI.Application.Abstractions.Sys.Dtos;
using JESAI.AutoMapper.ObjectMapping;
using JESAI.Core.Attributes;
using JESAI.DDD.Services;
using JESAI.Platform.Domain.Admin.Repositories;
using JESAI.Platform.Domain.Sys.Entities;
using JESAI.Platform.Domain.Sys.Repositories;
using JESAI.Uow;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JESAI.Application.Service.Sys
{
    [AppService]
    public class OperationLogService : ApplicationService,IOperationLogService
    {
        private readonly IOperationLogRepository _operationLogRepository;
        private readonly IAppRepository _appRepository;
        private readonly ILogger<OperationLogService> _logger;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        public OperationLogService(IOperationLogRepository operationLogRepository, IAppRepository appRepository,ILogger<OperationLogService> logger, IUnitOfWorkManager unitOfWorkManager)
        {
            _operationLogRepository = operationLogRepository;
            _logger = logger;
            _unitOfWorkManager = unitOfWorkManager;
            _appRepository = appRepository;
        }


        public void AddOperationLogAsync(OperationLogDto operationLog)
        {
            //Task.Run(async () =>
            //{
                using (var uow = _unitOfWorkManager.CreateContext())
                {
                    try
                    {

                        string[] appNames = _appRepository._DbQueryable.Where(p => p.AppId == operationLog.OperatorAppKey).Select(p => p.Name).ToArray();
                        var entity = operationLog.MapTo<OperationLogEntity>();
                        entity.Id = Guid.NewGuid().ToString();
                        entity.Operator = appNames.FirstOrDefault();
                        _operationLogRepository.Insert(entity);
                        uow.Commit();

                    }
                    catch (Exception ex)
                    {
                        uow.Rollback();
                        _logger.LogException(ex);
                    }
                }
            //});
        }
    }
}
